var topsun = topsun || {};

/**
 * 将删除表格行记录
 * 
 * @example topsun.removeFun($('#datagridId'),uri)
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery 
 * 
 */
topsun.removeFun = function($grid, uri){

	var arr =$grid.datagrid('getChecked');
	if(arr.length <=0){
		$.messager.show({
			title:'提示信息!',
			msg:'至少选择一行记录进行删除!'
		});
		return;
	} else {
		$.messager.confirm('提示信息' , '确认删除?' , function(r){
				if(r){
						var ids = '';
						for(var i =0 ;i<arr.length;i++){
							ids += arr[i].id + ',' ;
						}
						ids = ids.substring(0 , ids.length-1);
						$.post(topsun.contextPath + uri ,
								{ids:ids} , function(result){
								if (result.success){
									$grid.datagrid('reload');
									$grid.datagrid('unselectAll');
									$.messager.show({
										title:'提示信息!' , 
										msg:'操作成功!'
									});
								}else {
									$.messager.show({	// show error message
										title: 'Error',
										msg: 'error'
									});
								}
						},'json');
						
				} 
		});
	}
	
};
topsun.removeNFun = function($grid, uri){

	var arr =$grid.datagrid('getChecked');
	if(arr.length <=0){
		$.messager.show({
			title:'提示信息!',
			msg:'至少选择一行记录进行删除!'
		});
		return;
	} else {
		$.messager.confirm('提示信息' , '确认删除?' , function(r){
				if(r){
						var ids = '';
						for(var i =0 ;i<arr.length;i++){
							ids += arr[i].id + ',' ;
						}
						ids = ids.substring(0 , ids.length-1);
						$.post(topsun.contextPath + uri ,
								{ids:ids,idtype:'1'} , function(result){
								if (result.success){
									$grid.datagrid('reload');
									$grid.datagrid('unselectAll');
									$.messager.show({
										title:'提示信息!' , 
										msg:'操作成功!'
									});
								}else {
									$.messager.show({	// show error message
										title: 'Error',
										msg: 'error'
									});
								}
						},'json');
						
				} 
		});
	}
	
};
/**
 * 添加记录，弹出对话框，iframe中为一个jsp
 * 
 * @example topsun.addFun($('#datagridId'),uri)
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery 
 * 
 */
topsun.addFun = function($grid, uri) {
	  var dialog = parent.topsun.modalDialog({
			title : '新增',
			iconCls : 'icon-add',
			url : topsun.contextPath + uri,
			buttons : [ {
				text : '确定',
				iconCls : 'icon-ok',
				handler : function() {
					dialog.find('iframe').get(0).contentWindow.submitForm(dialog, $grid);
				}
			} ,
			{
				text : '关闭',
				iconCls : 'icon-cancel',
				handler : function() {
					dialog.find('iframe').get(0).contentWindow.cancleform(dialog, $grid);
				}
			} ]
		});
};

/**
 * 编辑记录，弹出对话框，iframe中为一个jsp
 * 
 * @example topsun.editFun($('#datagridId'),uri)
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery 
 * 
 */
topsun.editFun = function($grid, uri) {
	
	var arr =$grid.datagrid('getSelections');
	if(arr.length != 1){
		$.messager.show({
			title:'提示信息!',
			msg:'只能选择一行记录进行修改!'
		});
	}else{
	  var row = $grid.datagrid('getSelected');
	  if (row){
		  var dialog = parent.topsun.modalDialog({
				title : '编辑',
				iconCls : 'icon-edit',
				url : topsun.contextPath + uri+'?id='+row.id,
				buttons : [ {
					text : '确定',
					iconCls : 'icon-ok',
					handler : function() {
						dialog.find('iframe').get(0).contentWindow.submitForm(dialog, $grid);
					}
				} ,
				{
					text : '关闭',
					iconCls : 'icon-cancel',
					handler : function() {
						dialog.find('iframe').get(0).contentWindow.cancleform(dialog, $grid);
					}
				} ]
			});
	   }
	}
};

topsun.copyFun = function($grid, uri) {
	
	var arr =$grid.datagrid('getSelections');
	if(arr.length != 1){
		$.messager.show({
			title:'提示信息!',
			msg:'只能选择一行记录!'
		});
	}else{
	  var row = $grid.datagrid('getSelected');
	  if (row){
		  var dialog = parent.topsun.modalDialog({
				title : '拷贝',
				iconCls : 'icon-edit',
				url : topsun.contextPath + uri+'?showmodel=copy&id='+row.id,
				buttons : [ {
					text : '确定',
					iconCls : 'icon-ok',
					handler : function() {
						dialog.find('iframe').get(0).contentWindow.submitForm(dialog, $grid);
					}
				} ,
				{
					text : '关闭',
					iconCls : 'icon-cancel',
					handler : function() {
						dialog.find('iframe').get(0).contentWindow.cancleform(dialog, $grid);
					}
				} ]
			});
	   }
	}
};
/**
 * 查看记录，弹出对话框，iframe中为一个jsp
 * 
 * @example topsun.viewFun($('#datagridId'),uri)
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery 
 * 
 */
topsun.viewFun = function($grid, uri) {
	var arr =$grid.datagrid('getSelections');
	if(arr.length == 1){
		
	  var row = $grid.datagrid('getSelected');
	  if (row){
		  var dialog = parent.topsun.modalDialog({
				title : '编辑',
				iconCls : 'icon-edit',
				url : topsun.contextPath + uri+'?id='+row.id,
				buttons : [ 
				{
					text : '关闭',
					iconCls : 'icon-cancel',
					handler : function() {
						dialog.find('iframe').get(0).contentWindow.cancleform(dialog, $grid);
					}
				} ]
			});
	   }
	}
	
};

topsun.exportExcel = function($grid, uri, $form){
	$.messager.confirm('提示信息' , '确认导出当前分页，取消导出所有数据?' ,  function(r){
		if(r){
			//get方式
			//页码，一页数量，排序列，排序方向
			var options = $grid.datagrid('getPager').data("pagination").options;
			var params = 'page='+options.pageNumber+'&rows='+options.pageSize;
			if(typeof(sortName)!="undefined" && sortName!='' && typeof(sortOrder)!="undefined" && sortOrder!=''  ){
				params+='&sort='+sortName+'&order='+sortOrder;
			}
			var formparams = '';
			//增加过滤条件
			if($form !='undefined' && $form!='' ){
				formparams = $form.serialize();  
			}
			var url =topsun.contextPath + uri +'?'+params+'&'+formparams;  
	 	 	window.location.href = url;
			
		} else{
			var params = 'exportmodel=all';
			if(typeof(sortName)!="undefined" && sortName!='' && typeof(sortOrder)!="undefined" && sortOrder!=''  ){
				params+='&sort='+sortName+'&order='+sortOrder;
			}
			var formparams = '';
			//增加过滤条件
			if($form !='undefined' && $form!='' ){
				formparams = $form.serialize();  
			}
			var url =topsun.contextPath + uri +'?'+params+'&'+formparams;  
	 	 	window.location.href = url;
		}
	}
	);
};

/**
 * 将form表单元素的值序列化成对象
 * 
 * @example topsun.serializeObject($('#formId'))
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery
 * 
 * @returns object
 */
topsun.serializeObject = function(form) {
	var o = {};
	$.each(form.serializeArray(), function(index) {
		if (this['value'] != undefined && this['value'].length > 0) {// 如果表单项的值非空，才进行序列化操作
			if (o[this['name']]) {
				o[this['name']] = o[this['name']] + "," + this['value'];
			} else {
				o[this['name']] = this['value'];
			}
		}
	});
	return o;
};
/**
 * 更改easyui加载panel时的提示文字
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery,EasyUI
 */
$.extend($.fn.panel.defaults, {
	loadingMessage : '加载中....'
});

/**
 * 更改easyui加载grid时的提示文字
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery,EasyUI
 */
$.extend($.fn.datagrid.defaults, {
	loadMsg : '数据加载中....'
});

/**
 * panel关闭时回收内存，主要用于layout使用iframe嵌入网页时的内存泄漏问题
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery,EasyUI
 * 
 */
$.extend($.fn.panel.defaults, {
	onBeforeDestroy : function() {
		var frame = $('iframe', this);
		try {
			if (frame.length > 0) {
				for (var i = 0; i < frame.length; i++) {
					frame[i].src = '';
					frame[i].contentWindow.document.write('');
					frame[i].contentWindow.close();
				}
				frame.remove();
				if (navigator.userAgent.indexOf("MSIE") > 0) {// IE特有回收内存方法
					try {
						CollectGarbage();
					} catch (e) {
					}
				}
			}
		} catch (e) {
		}
	}
});

topsun.modalDialog = function(options) {
	var opts = $.extend({
		title : '&nbsp;',
		width : 640,
		height : 480,
		modal : true,
		onClose : function() {
			$(this).dialog('destroy');
		}
	}, options);
	opts.modal = true;// 强制此dialog为模式化，无视传递过来的modal参数
	if (options.url) {
		opts.content = '<iframe id="" src="' + options.url + '" allowTransparency="true" scrolling="auto" width="100%" height="98%" frameBorder="0" name=""></iframe>';
	}
	return $('<div/>').dialog(opts);
};


/**
 * 扩展tree和combotree，使其支持平滑数据格式
 * 
 * @author yuxiaobei
 * 
 * @requires jQuery,EasyUI
 * 
 */
topsun.loadFilter = {
	loadFilter : function(data, parent) {
		var opt = $(this).data().tree.options;
		var idField, textField, parentField;
		if (opt.parentField) {
			idField = opt.idField || 'id';
			textField = opt.textField || 'text';
			parentField = opt.parentField || 'pid';
			var i, l, treeData = [], tmpMap = [];
			for (i = 0, l = data.length; i < l; i++) {
				tmpMap[data[i][idField]] = data[i];
			}
			for (i = 0, l = data.length; i < l; i++) {
				if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {
					if (!tmpMap[data[i][parentField]]['children'])
						tmpMap[data[i][parentField]]['children'] = [];
					data[i]['text'] = data[i][textField];
					tmpMap[data[i][parentField]]['children'].push(data[i]);
				} else {
					data[i]['text'] = data[i][textField];
					treeData.push(data[i]);
				}
			}
			return treeData;
		}
		return data;
	}
};
$.extend($.fn.combotree.defaults, topsun.loadFilter);
$.extend($.fn.tree.defaults, topsun.loadFilter);


$.extend($.fn.treegrid.defaults, {
	
	loadFilter : function(data, parentId) {
		var opt = $(this).data().treegrid.options;
		var idField, treeField, parentField;
		if (opt.parentField) {
			idField = opt.idField || 'id';
			treeField = opt.textField || 'text';
			parentField = opt.parentField || 'pid';
			var i, l, treeData = [], tmpMap = [];
			for (i = 0, l = data.length; i < l; i++) {
				tmpMap[data[i][idField]] = data[i];
			}
			for (i = 0, l = data.length; i < l; i++) {
				if (tmpMap[data[i][parentField]] && data[i][idField] != data[i][parentField]) {
					if (!tmpMap[data[i][parentField]]['children'])
						tmpMap[data[i][parentField]]['children'] = [];
					data[i]['text'] = data[i][treeField];
					tmpMap[data[i][parentField]]['children'].push(data[i]);
				} else {
					data[i]['text'] = data[i][treeField];
					treeData.push(data[i]);
				}
			}
			return treeData;
		}
		return data;
	}
});